import React, { Component } from "react";
import { connect } from "react-redux";
import { messages, queryCurrencyPrecision } from "share/common";
import AdvancedTable from "components/advanced-table";
import {
  Icon,
  Modal,
  Button,
  Radio,
  Spin,
  notification,
  message,
  Tooltip,
  Popconfirm,
} from "antd";
import SlideFrame from "components/slide-frame";
import receiptLabel from "./searchForm-components/RECEIPT_LABEL";
import receiptTitle from "./searchForm-components/RECEIPT_TITLE";
import receiptInvalidStatus, {
  RECEIPT_INVALID_STATUS_OPTION,
} from "./searchForm-components/RECEIPT_INVALID_STATUS";
import ScanSnap from "components/scan-snap";
import expenseService from "containers/my-account/expense.service";
import "styles/financial-management/invoice-management-platform.scss";
import invoiceManagementPlatformService from "./invoice-management-platform.service";
import FileSaver from "file-saver";
import invoiceBagApproveService from "../invoice-bag-approve/invoice-bag-approve.service";
import CreateInvoice from "containers/my-account/create-invoice";
import Invoice from "containers/my-account/invoice";
import baseService from "share/base.service";

class InvoiceManagementPlatform extends Component {
  advancedTableRef = null;

  state = {
    loading: false,
    showOCRFlag: false,
    gettingTitle: false,
    loadingInvoice: null,
    showEditInvoiceFlag: false,
    showViewInvoiceFlag: false,
    nowInvoice: null,
    currencyList: [],
    exportDisabled: true,
  };

  RECEIPT_VAT_INVOICE_OPTION = [
    {
      label: messages("common.all") /*全部*/,
      key: "all",
    },
    {
      label: messages("common.yes") /*是*/,
      key: 1,
    },
    {
      label: messages("common.no") /*否*/,
      key: 0,
    },
  ];

  searchForm = [
    receiptLabel,
    receiptTitle,
    receiptInvalidStatus,
    {
      id: "RECEIPT_BILL_DATE",
      label: messages("financial-management.key613") /*开票日期*/,
      component: "DateRangePicker",
      parser: (value) =>
        value
          ? {
              RECEIPT_BILL_DATE: {
                symbol: "BETWEEN_AND",
                values: value.map((item) =>
                  item ? item.format("YYYY-MM-DD") : null
                ),
              },
            }
          : null,
    },
    {
      id: "RECEIPT_CREATE_DATE",
      label: messages("financial-management.key901") /*扫描日期*/,
      component: "DateRangePicker",
      parser: (value) =>
        value
          ? {
              RECEIPT_CREATE_DATE: {
                symbol: "BETWEEN_AND",
                values: value.map((item) =>
                  item ? item.format("YYYY-MM-DD") : null
                ),
              },
            }
          : null,
    },
    {
      id: "RECEIPT_VAT_INVOICE",
      label: messages("financial-management.key902") /*是否可抵扣*/,
      initialValue: "all",
      component: (
        <Radio.Group>
          {this.RECEIPT_VAT_INVOICE_OPTION.map((item) => (
            <Radio key={item.key} value={item.key}>
              {item.label}
            </Radio>
          ))}
        </Radio.Group>
      ),
      tagParser: (value) =>
        this.RECEIPT_VAT_INVOICE_OPTION.find((item) => item.key === value)
          .label,
      parser: (value) =>
        value !== "all"
          ? {
              RECEIPT_VAT_INVOICE: {
                symbol: "EQUALS",
                values: [value],
              },
            }
          : null,
    },
  ];

  componentDidMount() {
    const { user } = this.props;
    this.setState({ gettingTitle: true, loading: true });
    expenseService
      .getTitleList(user.userOID)
      .then((res) => {
        this.setState({ showOCRFlag: res.data.showOCRFlag });
      })
      .finally(() => {
        this.setState({ gettingTitle: false });
      });
    baseService
      .getAllCurrencyByLanguage("zh_cn", user.userOID, true)
      .then((res) => {
        this.setState({ currencyList: res.data });
      })
      .finally((e) => {
        this.setState({ loading: false });
      });
  }

  renderOperationColumns = (id, record) => {
    let editOperation = (
      <a onClick={() => this.handleClickInvoice(id, true)}>
        {messages("financial-management.key500") /*编辑*/}
      </a>
    );
    let viewOperation = (
      <a onClick={() => this.handleClickInvoice(id)}>
        {messages("common.view") /*查看*/}
      </a>
    );
    return id === this.state.loadingInvoice ? (
      <Spin />
    ) : (
      <span>
        <Popconfirm
          title={
            messages("financial-management.key749") /*你确定要删除这张发票吗？*/
          }
          onConfirm={() => this.handleDeleteInvoice(id)}
        >
          <a>{messages("financial-management.key501") /*删除*/}</a>
        </Popconfirm>
        <span className="ant-divider" />
        {record.checkResult === "R_0000" ? viewOperation : editOperation}
      </span>
    );
  };

  columns = [
    {
      dataIndex: "type",
      title: messages("common.invoice.type") /*发票类型*/,
      width: 200,
      render: (text) => (
        <div className="bad-table-cell" style={{ width: 184 }}>
          <Tooltip title={text} placement="topLeft">
            {text}
          </Tooltip>
        </div>
      ),
    },
    {
      dataIndex: "vatInvoice",
      title: messages("financial-management.key902") /*是否可抵扣*/,
      width: 150,
      render: (vatInvoice) =>
        vatInvoice
          ? messages("common.yes") /*是*/
          : messages("common.no") /*否*/,
    },
    {
      dataIndex: "billingCode",
      title: messages("financial-management.key611") /*发票代码*/,
      width: 200,
      render: (text) => (
        <Tooltip title={text} placement="topLeft">
          {text || "-"}
        </Tooltip>
      ),
    },
    {
      dataIndex: "billingNo",
      title: messages("financial-management.key612") /*发票号码*/,
      width: 100,
      render: (text) => (
        <div className="bad-table-cell" style={{ width: 84 }}>
          <Tooltip title={text} placement="topLeft">
            {text || "-"}
          </Tooltip>
        </div>
      ),
    },
    {
      dataIndex: "billingTime",
      title: messages("financial-management.key613") /*开票日期*/,
      width: 150,
      render: (billingTime) =>
        billingTime ? new Date(billingTime * 1000).format("yyyy-MM-dd") : "-",
      sorter: (a, b) => a.billingTime - b.billingTime,
    },
    {
      dataIndex: "vatInvoiceCurrencyCode",
      title: messages("financial-management.key405") /*币种*/,
      width: 72,
      render: (text) => (
        <Tooltip title={text} placement="topLeft">
          {text}
        </Tooltip>
      ),
    },
    {
      dataIndex: "feeWithoutTax",
      title: messages("financial-management.key614") /*金额合计*/,
      width: 100,
      render: (feeWithoutTax, record) =>
        feeWithoutTax === null ? (
          <span className="money-cell">-</span>
        ) : (
          this.filterMoney(
            feeWithoutTax / 100,
            queryCurrencyPrecision(record.vatInvoiceCurrencyCode)
          )
        ),
    },
    {
      dataIndex: "taxRate",
      title: messages("financial-management.key747") /*税率*/,
      width: 100,
      render: (taxRate) => (taxRate === null ? "-" : `${taxRate * 100}%`),
    },
    {
      dataIndex: "tax",
      title: messages("common.tax") /*税额*/,
      width: 100,
      render: (tax, record) =>
        tax === null ? (
          <span className="money-cell">-</span>
        ) : (
          this.filterMoney(
            (tax || 0) / 100,
            queryCurrencyPrecision(record.vatInvoiceCurrencyCode)
          )
        ),
    },
    {
      dataIndex: "fee",
      title: messages("financial-management.key616") /*价税合计*/,
      width: 100,
      render: (fee, record) =>
        this.filterMoney(
          fee / 100,
          queryCurrencyPrecision(record.vatInvoiceCurrencyCode)
        ),
    },
    {
      dataIndex: "checkCode",
      title: messages("financial-management.key928") /*校验码*/,
      width: 200,
      render: (text) => (
        <Tooltip title={text} placement="topLeft">
          {text || "-"}
        </Tooltip>
      ),
    },
    {
      dataIndex: "invoiceGoods",
      title: messages("financial-management.key748") /*发票商品服务名称*/,
      width: 200,
      render: (invoiceGoods) => {
        let text =
          invoiceGoods.map((goods) => goods.goodsName).join("、") || "-";
        return (
          <div className="bad-table-cell" style={{ width: 184 }}>
            <Tooltip
              title={text}
              overlayStyle={{ width: 200, whiteSpace: "pre-wrap" }}
              placement="topLeft"
            >
              {text}
            </Tooltip>
          </div>
        );
      },
    },
    {
      dataIndex: "title",
      title: messages("financial-management.key903") /*购买方抬头*/,
      width: 200,
      render: (text) => (
        <Tooltip title={text} placement="topLeft">
          {text || "-"}
        </Tooltip>
      ),
    },
    {
      dataIndex: "draweeNo",
      title: messages("financial-management.key904") /*购买方纳税人识别号*/,
      width: 200,
      render: (text) => (
        <Tooltip title={text} placement="topLeft">
          {text || "-"}
        </Tooltip>
      ),
    },
    {
      dataIndex: "payee",
      title: messages("financial-management.key905") /*销售方抬头*/,
      width: 200,
      render: (text) => (
        <Tooltip title={text} placement="topLeft">
          {text || "-"}
        </Tooltip>
      ),
    },
    {
      dataIndex: "payeeNo",
      title: messages("financial-management.key906") /*销售方纳税人识别号*/,
      width: 200,
      render: (text) => (
        <Tooltip title={text} placement="topLeft">
          {text || "-"}
        </Tooltip>
      ),
    },
    {
      dataIndex: "invalidStatus",
      title: messages("financial-management.key647") /*发票状态*/,
      width: 150,
      render: (invalidStatus) => {
        let statusOption = RECEIPT_INVALID_STATUS_OPTION.find(
          (item) => item.key === invalidStatus
        );
        return statusOption ? statusOption.label : "-";
      },
    },
    {
      dataIndex: "createdDate",
      title: messages("financial-management.key901") /*扫描日期*/,
      width: 150,
      render: (createdDate) =>
        createdDate ? new Date(createdDate).format("yyyy-MM-dd") : "-",
    },
    {
      dataIndex: "createdByUser",
      title: messages("financial-management.key929") /*上传者*/,
      width: 200,
      render: (createdByUser) =>
        createdByUser ? (
          <Tooltip
            title={`${createdByUser.employeeId}-${createdByUser.fullName}`}
            placement="topLeft"
          >
            {createdByUser.employeeId}-{createdByUser.fullName}
          </Tooltip>
        ) : (
          "-"
        ),
    },
    {
      dataIndex: "id",
      title: messages("financial-management.key254") /*操作*/,
      width: 100,
      render: this.renderOperationColumns,
    },
  ];

  service = (page, size, searchParams) => {
    let conditionList = [];
    Object.keys(searchParams).map((key) => {
      if (searchParams[key]) {
        conditionList.push({
          queryKey: key,
          ...searchParams[key],
        });
      }
    });
    const params = {
      conditionList,
      entityType: "invoice",
    };
    return invoiceManagementPlatformService.getInvoiceList(page, size, params);
  };

  handleClickInfo = () => {
    Modal.info({
      title: messages("financial-management.key414") /*说明*/,
      content: (
        <div>
          <p>
            {
              messages("financial-management.key777")
              /*1.【扫描发票】：请购买富士通iX500型号扫描仪，用于批量扫描发票。
              建议统一大小和材质的发票在一批扫，不同大小发票一起扫描容易卡纸。*/
            }
          </p>
          <p>
            {
              messages("financial-management.key778")
              /*2.【扫描发票】：若按钮为禁用则表示没有连接扫描仪或当前系统不支持
              （目前仅支持安装了仪器驱动的windows系统，请保持系统端口8089为仪器所用），连接成功后请刷新页面。*/
            }
          </p>
          <p>
            {
              messages("financial-management.key907")
              /*3.【关于重复验证】：发票管理平台扫描的发票，仅与发票管理平台扫描的发票进行同发票类型验重；
              非发票管理平台扫描的发票，不与发票管理平台扫描的发票进行重复校验。*/
            }
          </p>
        </div>
      ),
    });
  };

  export = () => {
    this.setState({ exporting: true });
    invoiceManagementPlatformService.exportReceipt().then((res) => {
      let b = new Blob([res.data], {
        type:
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });
      let name =
        `${messages("financial-management.key908") /*发票管理平台导出*/}` +
        `${new Date().format("yyyyMMddhhmmss")}`;
      FileSaver.saveAs(b, `${name}.xlsx`);
      this.setState({ exporting: false });
    });
  };

  handleScan = (base64) => {
    const key = `open${Date.now()}`;
    notification.open({
      key,
      message: messages("financial-management.key782") /*识别中...*/,
      icon: <Icon type="loading" />,
      duration: null,
    });
    invoiceManagementPlatformService
      .scanBase64(base64)
      .then((res) => {
        if (res.data.success) {
          let method = "info";
          switch (res.data.code) {
            case 130113:
              method = "success";
              break;
            case 130114:
              method = "warning";
              break;
            case 130115:
              method = "error";
              break;
          }
          this.advancedTableRef.getList();
          notification.close(key);
          notification[method]({
            message: res.data.message,
            duration: 4,
          });
        }
      })
      .catch(() => {
        notification.close(key);
      });
  };

  handleClickInvoice = (id, isEdit) => {
    const { loadingInvoice } = this.state;
    if (loadingInvoice) {
      message.error(messages("financial-management.key750") /*请等待*/);
      return;
    }
    this.setState({ loadingInvoice: id });
    invoiceBagApproveService.getInvoiceDetail(id).then((res) => {
      this.setState({ nowInvoice: res.data }, () => {
        let viewParams = isEdit ? "showEditInvoiceFlag" : "showViewInvoiceFlag";
        this.setState({ [viewParams]: true, loadingInvoice: null });
      });
    });
  };

  handleDeleteInvoice = (id) => {
    this.setState({ loading: true });
    invoiceBagApproveService.deleteInvoice(id).then(() => {
      message.success(messages("common.operate.success") /*操作成功*/);
      this.advancedTableRef.getList();
    });
  };

  onSaveInvoice = () => {
    this.setState({ showEditInvoiceFlag: false });
    this.advancedTableRef.getList();
  };

  getExpandedRender = (record) => {
    if (record.receiptLabels) {
      return record.receiptLabels
        .filter((item) => item.type !== "INSP_SUCCEEDED")
        .map((item) => item.name)
        .join(",");
    } else {
      return null;
    }
  };

  render() {
    const {
      showOCRFlag,
      exporting,
      gettingTitle,
      exportDisabled,
      nowInvoice,
      showViewInvoiceFlag,
      showEditInvoiceFlag,
      currencyList,
    } = this.state;
    const { user, company, profile } = this.props;
    return (
      <div className="full-height-page invoice-management-platform">
        <AdvancedTable
          index
          columns={this.columns}
          onRef={(ref) => (this.advancedTableRef = ref)}
          title={messages("financial-management.key909") /*发票管理平台*/}
          searchForm={this.searchForm}
          service={this.service}
          expandedRowRender={this.getExpandedRender}
          expandAll
          onGetData={(data, pagination) =>
            this.setState({ exportDisabled: pagination.total === 0 })
          }
          rowKey="id"
          footer={
            <span className="button-area">
              {gettingTitle ? (
                <Spin className="scan-snap-button" />
              ) : (
                showOCRFlag && (
                  <span className="scan-snap-button">
                    <ScanSnap
                      buttonProps={{ type: "primary" }}
                      onScan={this.handleScan}
                    >
                      {messages("financial-management.key783") /*扫描发票*/}
                    </ScanSnap>
                    <Icon
                      type="info-circle"
                      onClick={this.handleClickInfo}
                      className="scan-info"
                    />
                  </span>
                )
              )}
              <Button
                onClick={this.export}
                loading={exporting}
                disabled={exportDisabled}
              >
                {messages("financial-management.key294") /*导出数据*/}
              </Button>
            </span>
          }
        />
        {nowInvoice && (
          <SlideFrame
            content={CreateInvoice}
            show={showEditInvoiceFlag}
            hasFooter={false}
            params={{
              invoiceUserFp: profile,
              fromVICP: true,
              userOID: user.userOID,
              receipt: nowInvoice,
              currencyList,
              createType: 2,
              receiptOperateScene: 3,
              invoiceOID: nowInvoice ? nowInvoice.invoiceOID : null,
              onCreate: this.onSaveInvoice,
              receiptList: [],
              onBack: () => this.setState({ showEditInvoiceFlag: false }),
              currency:
                nowInvoice.vatInvoiceCurrencyCode || company.baseCurrency,
            }}
            onClose={() => this.setState({ showEditInvoiceFlag: false })}
            afterClose={this.toState({
              showEditInvoiceFlag: false,
              nowInvoice: null,
            })}
            title={messages("financial-management.key755") /*编辑发票*/}
          />
        )}
        {nowInvoice && (
          <SlideFrame
            content={Invoice}
            show={showViewInvoiceFlag}
            hasFooter={false}
            params={{
              invoiceList: [nowInvoice],
              disabledEdit: true,
              onBack: () => this.setState({ showEditInvoiceFlag: false }),
            }}
            afterClose={this.toState({ nowInvoice: null })}
            onClose={() => this.setState({ showViewInvoiceFlag: false })}
            title={messages("financial-management.key756") /*查看发票*/}
          />
        )}
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user,
    profile: state.login.profile,
  };
}

export default connect(mapStateToProps)(InvoiceManagementPlatform);
